<?php
/**
 * @Author 张超.
 * @Copyright http://www.zhangchao.name
 * @Email 416716328@qq.com
 * @DateTime 2018/5/9 19:11
 * @Desc
 */

namespace app\run\controller;
use app\common\controller\Run;
use app\run\model\Admin;
use app\run\model\AuthGroupAccess;
use think\captcha\Captcha;
use think\Db;
use think\facade\Config;
use think\facade\Session;

class Login extends Run
{
    protected $run;
    protected function initialize()
    {
        return parent::initialize(); // TODO: Change the autogenerated stub
    }

    public function index(){
        Session::set(Config::get("auth.DEFAULT_LOGIN_SESSION"),null);
        Session::set('is_login',false);
        return $this->fetch();
    }
    public function do_login(){
        if ($this->request->isAjax()){
            //数据验证
            $validate = $this->validate(input("post."),'app\run\validate\Admin');
            if ($validate !== true)$this->ajaxRuturn(400,$validate);
            //查询用户信息
            $admin = new Admin();
            //组装条件
            $map[] = ['name','eq',input("post.name")];
            $result = $admin->where($map)->find();
            if (!$result)$this->ajaxRuturn(400,"用户名错误！");
            //验证密码
            if (!password_verify(input("password"),$result['password'])){
                $this->ajaxRuturn(400,"密码错误");
            }else{
                //更新登录时间以及登录ip
                $data['ip'] = $this->request->ip();
                $data['last_time'] = date("Y-m-d H:i:s");
                $saveResult = $admin->save($data,['id'=>$result['id']]);
                if (!$saveResult)$this->ajaxRuturn(400,"登录失败！");
                //密码正确之后、将密码进行存储、存储方式为 转json之后base64、然后加上一个随机6位的数字
                Session::set(Config::get("auth.DEFAULT_LOGIN_SESSION"),base64_encode(json_encode($result) . rand(100000,999999)));
                $this->ajaxRuturn(200,"登录成功！",url("run/index/down_page"));
            }
        }else{
            $this->run->ajaxRuturn(400,"请求方式有误！");
        }
    }
    public function captcha(){
        $config =    [
            // 验证码字体大小
            'fontSize'    =>    30,
            // 验证码位数
            'length'      =>    4,
            // 关闭验证码杂点
            'useNoise'    =>    true,
            // 是否画混淆曲线
            'useCurve' => false,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }
    public function out_login(){
        Session::set(Config::get("auth.DEFAULT_LOGIN_SESSION"),null);
        Session::set("is_login",false);
        // Session::set($this->request->ip(),null);
        return $this->redirect(url("Login/index"));
    }
    public function register(){
        if ($this->request->isAjax()){
            $post = input("post.");
            //判断验证码是否正确
            $captcha = new Captcha();
            if (!$captcha->check(input("post.captcha")))$this->ajaxRuturn(400,"验证码错误！");
            //数据验证
            $validate = $this->validate(input("post."),'app\run\validate\Admin');
            if ($validate !== true)$this->ajaxRuturn(400,$validate);
            Db::startTrans();
            try{
                $post['password'] = password_hash(input("post.password"),PASSWORD_BCRYPT);
                $post['exp_time'] = date("Y-m-d H:i:s");
                $post['day_number'] = read_cache("develop","day_number");//读取设置的每日限额
                $admin = new Admin();
                $result = $admin->allowField(true)->save($post);
                //插入权限关联
                $AuthGroupAccess = new AuthGroupAccess();
                $post['uid'] = $admin->getLastInsID();
                $resultAccess = $AuthGroupAccess->allowField(true)->save(['uid'=>$post['uid'],'group_id'=>6]);
                if ($result && $resultAccess){
                    Db::commit();
                    $this->ajaxRuturn(200,"注册成功、即将跳转登录！");
                }else{
                    Db::rollback();
                    $this->ajaxRuturn(400,"注册失败、请稍后再试！");
                }
            }catch (\Exception $e){
                $this->ajaxRuturn(400,$e->getMessage());
            }
        }else{
            return $this->fetch();
        }
    }
}